// Copyright 2012, Jun Chen .All rights reserved.
//
// Use of this source code is governed by a BSD-Style license that can be
// found in the License fule.
//
// Author: cpp.cheen at gmail dot com.


#ifndef EVT_DISPATHER_H
#define EVT_DISPATHER_H


#include    "pch_files.h"
#include    <boost/thread.hpp>
#include    <boost/smart_ptr.hpp>
#include    <vector>

class epoller;
class io_channel;
class timestamp;

class evt_dispather
{
    public:
        typedef     boost::function<void()>     functor;
        typedef     std::vector<functor>        functor_vec;
    public:
        /** Default constructor */
        evt_dispather();
        /** Default destructor */
        virtual ~evt_dispather();

        void    exit();

        /// the event loop to run for one more thread.
        void    main_loop();

        /// run functor
        /// run immediate if this mothrod called form main_loop,
        /// or save the functor and week up the main_loop to run.
        void    run_functor(functor func);

        /// run a functor after
        void    run_functor_after(functor func, int milisecond);

        /// run a functor at milisecond timne
        void    run_functor_at(functor func,const timestamp& run_time);

        /// can register channel,modify channel,remove channel
        x_int32 update_channel(io_channel*  channel);

        /// can register modify,remove io-event for a channel
        x_int32 update_subscribe_evt(io_channel*  channel);

    protected:
        x_bool  is_owner_thread();
        void    weekup();
        void    exec_pending_functor();
        void    pending_functor_append(functor func);
    private:
        boost::scoped_ptr<epoller>  m_ep_poller;
        //epoller     m_ep_poller;
        functor_vec m_pending_functors;
        x_bool      m_exit_flag;
        static const x_int32    m_poll_timeout_ms=500;
        boost::mutex    m_functor_vec_mutex;
        const boost::thread::id     m_owner_thread_id;
};

#endif // EVT_DISPATHER_H
